package com.huatai.vba.execute.action;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.huatai.vba.common.utils.*;
import com.huatai.vba.dal.jdbc.DBUtils;
import com.huatai.vba.dal.jdbc.SqlUtils;
import com.huatai.vba.dal.model.VbaFileAction;
import com.huatai.vba.execute.action.vo.*;
import com.huatai.vba.properties.Dbconfig;

@Service("icbcStartCreateActionExecutor")
public class IcbcStartCreateActionExecutor extends AbstractIcbcActionExecutor {

	private static final Logger logger = LoggerFactory.getLogger(IcbcStartCreateActionExecutor.class);

	@Override
	public void execute(VbaFileAction action) {
		try {
			String pstrSjsRepo = this.getRepoCode("SZ");
			String pstrSHRepo = this.getRepoCode("SH");
			String combi = convertSql(strOne);
			if (sjsmxToSjshb(pstrSjsRepo)) {
				genTsgh13812(pstrSHRepo);
			}
			doTssjsfx(combi);
			doTsjsmx(combi);
		} catch (Exception ex) {
			logger.error("系统异常", ex);
		}

	}

	private void getGDDMZM_1(String istrWTXH, String istrMarket, String ostrGDDMZM, Integer ostrIvestType)
			throws Exception {
		String strMarketID = null;
		if ("S".equals(istrMarket))
			strMarketID = "1";
		if ("H".equals(istrMarket))
			strMarketID = "2";
		String strSql = " select b.vc_fund_code,b.vc_fund_name, a.vc_stockholder_id ";
		strSql = strSql + " from tentrusts a,   Tfundinfo b ";
		strSql = strSql + " where a.l_fund_id = b.l_fund_id ";
		if (StringUtils.isBlank(istrWTXH)) {
			strSql = strSql + " and l_report_serial_no = '0'";
		} else {
			strSql = strSql + " and l_report_serial_no ='" + istrWTXH + "' ";
		}
		strSql = strSql + " And c_market_no ='" + strMarketID + "' ";
		List<Map<String, Object>> resultList = DBUtils.executeQuery(Dbconfig.TRADEDB, "trade_zc",
				Dbconfig.getPasswordByUserId("trade_zc"), strSql);
		if (ListUtils.isNotEmpty(resultList)) {
			ostrGDDMZM = (String) resultList.get(0).get("VC_FUND_CODE");
			ostrIvestType = 0;
		}

	}

	private boolean genTsgh13812(String pstrSHRepo) throws Exception {
		String combi = convertSql(strOne);
		String strSql = " select a.vc_seat_id ";
		strSql = strSql + " from ttradeseat a ,tfundinfo b ";
		strSql = strSql + " where a.l_fund_id = b.l_fund_id ";
		strSql = strSql + " and a.c_market_no = '1' ";
		strSql = strSql + " and a.c_trade = '1' ";
		strSql = strSql + " and vc_fund_code = any(" + combi + " )";
		strSql = strSql + " group by   a.vc_seat_id";
		List<Map<String, Object>> list = DBUtils.executeQuery(Dbconfig.TRADEDB, user,
				Dbconfig.getPasswordByUserId("trade_zc"), user);
		String[] arrSeatID = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			arrSeatID[i] = (String) list.get(i).get("VC_SEAT_ID");
		}
		// 清空数据
		vbaExtendsService.cleanTable("tsgh13812");

		for (int i = 0; i < arrSeatID.length; i++) {
			String strSeatID = arrSeatID[i];
			String sql = "select GDDM,GDXM,BCRQ,CJBH,GSDM,CJSL,BCYE,ZQDM,SBSJ,CJSJ,CJJG,CJJE,SQBH,BS,MJBH from GH"
					+ strSeatID;
			List<Map<String, Object>> l1 = vbaExtendsService.querySql(sql);
			for (int j = 0; j < l1.size(); j++) {
				Map<String, Object> map = l1.get(j);
				Tsgh13812 t = new Tsgh13812();

				t.setGdxm((String) map.get("GDXM"));
				t.setGsdm((String) map.get("GSDM"));
				t.setCjsl(Integer.valueOf(map.get("CJSL") + ""));
				t.setBcye((String) map.get("BCYE"));
				t.setSbsj((String) map.get("SBSJ"));
				t.setCjsj((String) map.get("CJSJ"));
				t.setCjjg(Double.valueOf(map.get("CJJG") + ""));
				t.setCjje(Double.valueOf(map.get("CJJE") + ""));
				t.setSqbh((String) map.get("SQBH"));
				t.setMjbh((String) map.get("MJBH"));

				String tmp_GDDM = (String) map.get("GDDM");
				String tmp_BCRQ = (String) map.get("BCRQ");
				String tmp_CJBH = (String) map.get("CJBH");
				String tmp_ZQDM = (String) map.get("ZQDM");
				String tmp_BS = (String) map.get("BS");
				String tmp_GDDMZM = null;
				if ("888880".equals(tmp_ZQDM)) {
					tmp_GDDMZM = getCombId(tmp_CJBH + "");
				} else {
					tmp_GDDMZM = getCombId(tmp_CJBH + "", tmp_BS + "", "1");
				}

				// '如果股东子码为空
				// '再根据zqdm的右三位，tradedate 到tuncompletelog里找出对应的fundid
				// '再到getgddmzm里找到对应的工行的编码

				// String strTmp = "";
				String strFundid = "";
				if ("".equals(tmp_GDDMZM)) {
					String strSql1 = " select B.VC_FUND_CODE,B.VC_FUND_NAME , A.*";
					strSql1 = strSql1 + " from tuncompletelog a";
					strSql1 = strSql1 + " INNER JOIN TFUNDINFO B ON B.L_FUND_ID = A.L_FUND_ID";
					strSql1 = strSql1 + " where a.vc_stockholder_id = '" + tmp_GDDM + "'";
					strSql1 = strSql1 + " and a.vc_inter_code like '7%"
							+ tmp_ZQDM.substring(tmp_ZQDM.length() - 3, tmp_ZQDM.length()) + "SS'";
					strSql1 = strSql1 + " and (l_trade_date <= " + tmp_BCRQ;
					strSql1 = strSql1 + " and l_complete_date > = " + tmp_BCRQ + ")";
					List<Map<String, Object>> resutList = DBUtils.executeQuery(Dbconfig.FATADB, user,
							Dbconfig.getPasswordByUserId(user), strSql1);
					if (ListUtils.isNotEmpty(resutList)) {
						Map<String, Object> tmpMap = resutList.get(0);
						strFundid = (String) tmpMap.get("VC_FUND_CODE");
						tmp_GDDMZM = getICBCCombi(strFundid);
					}
				}
				if ("".equals(tmp_GDDMZM)) {
					String tmpSql = "select b.vc_fund_code,a.*";
					tmpSql = tmpSql + " from TENTRUSTS a";
					tmpSql = tmpSql + " INNER JOIN TFUNDINFO B ON B.L_FUND_ID = A.L_FUND_ID";
					tmpSql = tmpSql + " where 1 = 1";
					tmpSql = tmpSql + " and vc_report_code like '7%"
							+ tmp_ZQDM.substring(tmp_ZQDM.length() - 3, tmp_ZQDM.length()) + "%' ";
					tmpSql = tmpSql + " and l_date =" + tmp_BCRQ;
					tmpSql = tmpSql + " and a.vc_stockholder_id ='" + tmp_GDDM + "'";
					tmpSql = tmpSql + " and a.vc_report_seat ='" + strSeatID + "'";
					List<Map<String, Object>> resutList = DBUtils.executeQuery(Dbconfig.FATADB, user,
							Dbconfig.getPasswordByUserId(user), tmpSql);
					if (ListUtils.isNotEmpty(resutList)) {
						Map<String, Object> tmpMap = resutList.get(0);
						strFundid = (String) tmpMap.get("VC_FUND_CODE");
						tmp_GDDMZM = getICBCCombi(strFundid);
					}
				}
				String tmp_HSLX = null;
				if (!chk_gddm(tmp_GDDM)) {
					tmp_HSLX = getHSLZ(tmp_CJBH, (String) tmp_BS, "1");
					if ("1".equals(tmp_HSLX)) {
						tmp_HSLX = "2";
					} else if ("2".equals(tmp_HSLX)) {
						tmp_HSLX = "3";
					} else if ("3".equals(tmp_HSLX)) {
						tmp_HSLX = "1";
					}
				} else {
					tmp_HSLX = getHSLZ((String) tmp_CJBH, (String) tmp_BS, "1");
				}

				// '投联账户的所有类型默认为1
				if ("777101".equals(tmp_GDDMZM) || "777102".equals(tmp_GDDMZM) || "777103".equals(tmp_GDDMZM)) {
					tmp_HSLX = "1";
				}
				if (pstrSHRepo.indexOf((String) tmp_ZQDM) >= 0) {
					tmp_HSLX = "1";
				}
				// 华泰人寿的例外
				if (StringUtils.isBlank(tmp_GDDMZM) && "B881498268".equals(tmp_GDDM)) {
					tmp_GDDMZM = "777777";
				}
				// '长城的例外
				if (StringUtils.isBlank(tmp_GDDMZM) && "B881879278".equals(tmp_GDDM)) {
					tmp_GDDMZM = "888888";
				}
				if (StringUtils.isNotBlank(tmp_GDDMZM)) {

					t.setGddm((String) tmp_GDDM);
					t.setBcrq((String) tmp_BCRQ);
					t.setCjbh((String) tmp_CJBH);
					t.setZqdm((String) tmp_ZQDM);
					t.setGddmzm(tmp_GDDMZM);
					t.setHslx(tmp_HSLX);
					t.setBs(tmp_BS);
					t.executeInsert(vbaExtendsService);
				}

			}

		}
		return true;
	}

	// 深交所明细转回报
	private boolean sjsmxToSjshb(String pstrSjsRepo) throws Exception {
		String tmpSql = " select a.* from sjsmx1 a ,hsfundid b where a.mxzxbh = b.cjbh ";
		List<Map<String, Object>> resultList = vbaExtendsService.querySql(tmpSql);
		Integer lngHBCJHM = 1;
		for (int i = 0; i < resultList.size(); i++) {
			Map<String, Object> tmpMap = resultList.get(i);
			Tssjshb ts = new Tssjshb();
			// '明细库里不再有cjhm，暂采用流水号递增
			String tmp_HBCJHM = lngHBCJHM + "";

			String tmp_HBZQDM = (String) tmpMap.get("MXZQDM");
			// '回报库的合同序号=6位mxjydy（交易单元） + 8位mxcjrq成交日期日期 + 8位 mxddbh
			String MXJYDY = (String) tmpMap.get("MXJYDY");
			String MXCJRQ = (String) tmpMap.get("MXCJRQ");
			String MXDDBH = (String) tmpMap.get("MXDDBH");
			String tmp_HBHTXH = MXJYDY + MXCJRQ + MXDDBH;
			ts.setHbhtxh(tmp_HBHTXH);
			// '股东代码 mxzqdh 证券帐号
			String tmp_HBGDDM = (String) tmpMap.get("MXZQZH");
			ts.setHbgddm(tmp_HBGDDM);
			// '成交数量 MXCJSL
			Double tmp_HBCJSL = tmpMap.get("MXCJSL") != null ? Double.valueOf(tmpMap.get("MXCJSL") + "") : null;
			// '成交价格
			Double tmp_HBCJJG = tmpMap.get("MXCJJG") != null ? Double.valueOf(tmpMap.get("MXCJJG") + "") : null;
			// '对方席位 MXZXBH的前6位
			String MXZXBH = (String) tmpMap.get("MXZXBH");
			String tmp_HBDFXW = MXZXBH.substring(0, 6);
			String tmp_HBDFGD = MXZXBH.substring(MXZXBH.length() - 10, MXZXBH.length());

			// '成交时间HBCJSJ取 MXYWLSH 流水号后8位
			String MXYWLSH = (String) tmpMap.get("MXYWLSH");
			String tmp_HBCJSJ = MXYWLSH.substring(MXYWLSH.length() - 8, MXYWLSH.length());
			ts.setHbcjsj(tmp_HBCJSJ);
			String tmp_HBCJRQ = DateUtils.generalDate(MXCJRQ, "yyyyMMdd", "yyyy-MM-dd");
			ts.setHbcjrq(tmp_HBCJRQ);
			String tmp_HBYWLB = null;

			String MXYWLB = (String) tmpMap.get("MXYWLB");
			Double MXSFJE = Double.valueOf(tmpMap.get("MXSFJE") + "");
			if ("JY00".equalsIgnoreCase(MXYWLB) || "JY01".equalsIgnoreCase(MXYWLB) || "HGCS".equalsIgnoreCase(MXYWLB)) {
				if (MXSFJE > 0) {
					tmp_HBYWLB = "0S";
				} else {
					tmp_HBYWLB = "0B";
				}
			} else if ("HGDQ".equalsIgnoreCase(MXYWLB)) {
				if (MXSFJE > 0) {
					tmp_HBYWLB = "9S";
				} else {
					tmp_HBYWLB = "9B";
				}
			}
			String tmp_HSLX = null;
			String tmp_GDDMZM = getCombId(MXZXBH, tmp_HBYWLB, "2");
			if (isSjshg(tmp_HBZQDM) && tmp_HBCJSL == 0) {

				tmp_HSLX = "1";
			} else {
				if (chk_gddm(tmp_HBGDDM)) {
					tmp_HSLX = getHSLZ(tmp_HBCJHM, tmp_HBYWLB, "2");
					if ("1".equals(tmp_HSLX)) {
						tmp_HSLX = "2";
					} else if ("2".equals(tmp_HSLX)) {
						tmp_HSLX = "3";
					} else if ("3".equals(tmp_HSLX)) {
						tmp_HSLX = "1";
					}
				} else {
					tmp_HSLX = getHSLZ(tmp_HBDFXW + tmp_HBDFGD, tmp_HBYWLB, "2");
				}
			}
			if ("777101".equals(tmp_GDDMZM) || "777102".equals(tmp_GDDMZM) || "777103".equals(tmp_GDDMZM)) {
				tmp_HSLX = "1";
			}
			ts.setHbcjhm(tmp_HBCJHM);
			ts.setHbzqdm(tmp_HBZQDM);
			ts.setHbcjsl(tmp_HBCJSL);
			ts.setHbcjjg(tmp_HBCJJG);
			ts.setHbdfxw(tmp_HBDFXW);
			ts.setHbdfgd(tmp_HBDFGD);
			ts.setHbywlb(tmp_HBYWLB);
			ts.setHBGDDMZM(tmp_GDDMZM);
			ts.setHBHSLX(tmp_HSLX);
			if (StringUtils.isNotBlank(tmp_GDDMZM)) {
				if (isSjshg(tmp_HBZQDM)) {
					ts.setHBHSLX(tmp_HSLX);
					ts.setHbcjjg(100d);
				}
				ts.executeInsert(vbaExtendsService);
				if ("0S".equals(tmp_HBYWLB)) {
					lngHBCJHM++;
					ts.setHbcjhm(lngHBCJHM + "");
					ts.setHbcjjg(Math.abs(Double.valueOf(MapUtils.getIgnoreCase(tmpMap, "mxCJJG") + "")));
					ts.setHbcjsl(0d);
					ts.setHbywlb("0B");
					ts.executeInsert(vbaExtendsService);
				}
				lngHBCJHM++;
			} else {
				logger.info("tmp_GDDMZM字段数据未空,跳过数据");
			}
			// '======下面是殷学东于2012年0615日添加的程序,用来处理深圳交易所回购到期的程序==========================
			// String tmp_htxhdate =
			// convertStrDateFormat(tmp_HBHTXH.substring(6, 14));
			// if (pstrSjsRepo.indexOf(tmp_HBZQDM) >= 0 &&
			// !tmp_htxhdate.equals(tmp_HBCJRQ)) {
			// String tmp_HisGDDMZM = getHisCombId(tmp_HBHTXH);
			// tmp_HSLX = getHSLZ(tmp_HBHTXH, tmp_HBYWLB, "2");
			// if (StringUtils.isBlank(tmp_HSLX)) {
			// tmp_HSLX = "1";
			// }
			// ts.setHBHSLX(tmp_HSLX);
			// ts.setHBGDDMZM(tmp_HisGDDMZM);
			// tmpSql = SqlUtils.generateSql(ts);
			// vbaExtendsService.executeSql(tmpSql);
			// }

			lngHBCJHM++;
		}
		return true;
	}

	private String getHisCombId(String tmp_HBHTXH) throws Exception {
		String tmp_seat = tmp_HBHTXH.substring(0, 6);
		String tmp_date = tmp_HBHTXH.substring(6, 14);
		String tmp_serial_no = tmp_HBHTXH.substring(14, 22);
		StringBuffer sb = new StringBuffer();
		sb.append(" select c.vc_fund_code COMBI_ID from thisentrusts  a,tcombi b,tfundinfo c where ");
		sb.append(" a.l_basecombi_id = b.l_combi_id");
		sb.append(" and b.l_fund_id = c.l_fund_id");
		sb.append(" and a.vc_report_seat ='").append(tmp_seat).append("'");
		sb.append(" and a.l_date='").append(tmp_date).append("'");
		sb.append(" and a.l_report_serial_no = '").append(tmp_serial_no).append("'");
		List<Map<String, Object>> list = DBUtils.executeQuery(Dbconfig.TRADEDB, "trade_zc",
				Dbconfig.getPasswordByUserId("trade_zc"), sb.toString());
		Map<String, Object> map = list.get(0);
		return map.get("COMBI_ID") + "";
	}

	/**
	 * '找股东代码，找到返回true，未找到返回false
	 * 
	 * @param istrGDDM
	 * @return
	 */
	private boolean chk_gddm(String istrGDDM) {
		String[] args = { "0899050622", "0508293128", "0509473512", "0899043874", "0899043875", "0010000134",
				"B881879278", "B880635710", "B880777978", "B881031561", "0509327697", "0510455186", "0899045183",
				"B881307093" };
		for (String s : args) {
			if (istrGDDM.indexOf(s) >= 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 生成特殊结算明细库
	 */
	private void doTsjsmx(String combi) throws Exception {
		String strGDDMZM = "";
		Integer strInvestType = 0;
		String tmp_FXWTXH = null;
		String strSql = "select * from jsmxjs946 ";
		List<Map<String, Object>> resultList = vbaExtendsService.querySql(strSql);
		for (Map<String, Object> map : resultList) {
			Jsmxjs946 js = new Jsmxjs946(map);
			Tsjsmxjs946 ts = BeanMapper.map(js, Tsjsmxjs946.class);
			tmp_FXWTXH = (String) map.get("SQBH");
			if (StringUtils.isBlank(tmp_FXWTXH)) {
				getGDDMZM_1(tmp_FXWTXH, "H", strGDDMZM, strInvestType);
				if (combi.indexOf(strGDDMZM) >= 0) {
					strGDDMZM = getICBCCombi(strGDDMZM);
					ts.setGDDMZM(strGDDMZM);
				}
			}
			ts.setHSLX(strInvestType);
			String insertSql = SqlUtils.generateSql(ts);
			vbaExtendsService.executeSql(insertSql);
		}
	}

	/**
	 * 生成特殊深交所发行库
	 * 
	 * @param combi
	 * @throws Exception
	 */
	private void doTssjsfx(String combi) throws Exception {
		String sql = "select *  from sjsfx ";
		List<Map<String, Object>> resultList = vbaExtendsService.querySql(sql);
		for (Map<String, Object> map : resultList) {
			Sjsfx sj = new Sjsfx(map);
			Tssjsfx100200 ts = BeanMapper.map(sj, Tssjsfx100200.class);
			String strGDDMZM = "";
			Integer strInvestType = 0;
			getGDDMZM_1(null, "S", strGDDMZM, strInvestType);
			if (combi.indexOf(strGDDMZM) >= 0) {
				strGDDMZM = getICBCCombi(strGDDMZM);
			}
			ts.setFXGDDMZM(strGDDMZM);
			ts.setFXHSLX(strInvestType);
			ts.executeInsert(vbaExtendsService);
		}

	}

}
